package com.zw.mes.config.shiro.realm;


import com.zw.mes.constant.Constant;
import com.zw.mes.entity.sys.Menu;
import com.zw.mes.entity.sys.Role;
import com.zw.mes.entity.sys.User;
import com.zw.mes.module.system.service.MenuService;
import com.zw.mes.module.system.service.RoleService;
import com.zw.mes.module.system.service.UserService;
import com.zw.mes.util.CommonUtils;
import com.zw.mes.util.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @Description: 自定义 realm 处理登录，权限
 *
 * @Author: China.sgl
 * @Date: 2020/7/30 9:42
 */
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = ShiroUtils.getUser();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 管理员拥有所有权限
        if (Constant.MANAGER.equals(user.getAccount())) {
            info.addRole("admin");
            info.addStringPermission("*:*:*");
        } else {
            List<Role> roles = roleService.findRoleByUserId(user.getId());
            List<Menu> menus = menuService.findMenuByUserId(user.getId());
            // 角色加入AuthorizationInfo认证对象
            for (Role role : roles) {
                info.addRole(role.getCode());
            }
            // 权限加入AuthorizationInfo认证对象
            for (Menu menu : menus) {
                info.addStringPermission(menu.getCode());
            }
        }

        /*info.addRole("admin");
        info.addStringPermission("*:*:*");*/

        Session session = ShiroUtils.getSession();
        session.setAttribute("roles", info.getRoles());
        session.setAttribute("permissions", info.getStringPermissions());
        session.setAttribute("loginUser",user);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String username = upToken.getUsername();
        String password = new String(upToken.getPassword());
        // 用户名或密码为空
        if (CommonUtils.isEmpty(username) || CommonUtils.isEmpty(password)) {
            throw new UnknownAccountException();
        }
        // 查询用户信息
        User user = userService.findUserByAccount(username);
        if (user == null) {
            throw new UnknownAccountException();
        }
        // 用户状态
        if (user.getStatus() == 0) {
            throw new LockedAccountException();
        }

        return new SimpleAuthenticationInfo(user, user.getPwd(), ByteSource.Util.bytes(user.getAccount()), getName());
    }

    /**
     * 清理 授权 缓存
     */
    public void clearCachedAuthorizationInfo() {
        clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }
}
